package org.mspring.mlog;

import freemarker.ext.jsp.TaglibFactory;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Gao Youbo
 * @since 2014年10月14日
 */
public class DispatcherServlet extends org.springframework.web.servlet.DispatcherServlet {

    private static final Logger LOG = LoggerFactory.getLogger(DispatcherServlet.class);

    public DispatcherServlet() {
        super();
    }

    public DispatcherServlet(WebApplicationContext webApplicationContext) {
        super(webApplicationContext);
    }

    private TemplateModel model;

    @Override
    protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
        exportWidgetTld(request, mv);
        super.render(mv, request, response);
    }

    /**
     * 将tag标签添加到环境变量
     *
     * @param request
     * @param mv
     */
    private void exportWidgetTld(HttpServletRequest request, ModelAndView mv) {
        try {
            if (model == null) {
                TaglibFactory factory = new TaglibFactory(request.getSession().getServletContext());
                model = factory.get("/WEB-INF/nbee.tld");
            }
            mv.getModel().put("m", model);
        } catch (TemplateModelException e) {
            LOG.error("加载TLD标签失败", e);
        }
    }

}
